package Clients;

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.*;

import java.sql.Date;
import java.sql.Time;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Scanner;

import Catalogue.*;
import Middle.*;


/**
 * Implements the GUI for the Backdoor client.
 * 
 * @author Michael Alexander Smith
 * @author Walter Reis
 * @version 1.0
 */

class BackDoorGUI implements KeyListener{
	private static final int height = 300; // Height of window
	private static final int width = 400; // Width of window

	private JLabel action = new JLabel();
	private JTextField input = new JTextField();
	private JTextField inputNo = new JTextField();
	private JTextArea output = new JTextArea();
	private JScrollPane scrollPane = new JScrollPane();
	private JButton addBtn = new JButton("Add");
	private JButton checkBtn = new JButton("Check");
	private JButton clearBtn = new JButton(Name.CLEAR);

	private Picture picture = new Picture(80, 80);
	private Product     product = null;            // Current product
	private Transaction transaction = new Transaction();
	private StockReadWriter stock     = null;

	private NumberFormat money = NumberFormat.getCurrencyInstance(Locale.UK);

	public BackDoorGUI(RootPaneContainer rpc, MiddleFactory mf) {
		try {
			stock = mf.makeStockReadWriter();
		} catch (Exception e) {
			System.out.println("Exception: " + e.getMessage());
		}
		
		Container container = rpc.getContentPane();
		Container rootWindow = (Container) rpc;
		container.setLayout(null);
		rootWindow.setSize(width, height);
		container.setBackground(Color.BLACK);

		Font f = new Font("Monospaced", Font.PLAIN, 12);

		addBtn.setBounds(16, 25 + 60 * 0, 80, 40);
		addBtn.addActionListener(transaction);
		addBtn.setIcon(new ImageIcon("src/images/ButtonTex/buttonTex.png")); 	//Changes the background image
	    addBtn.setVerticalTextPosition(JButton.CENTER); 						// Sets the text to the middle
	    addBtn.setHorizontalTextPosition(JButton.CENTER); 						//to avoid it bumping the image around
	    addBtn.setBackground(Color.BLACK); 			//Sets the background to black
	    addBtn.setBorder(null); 					//Removes the border around the button
	    addBtn.setForeground(Color.WHITE); 			//Sets the font color to white
	    addBtn.setContentAreaFilled(false); 		//Does not allow the background to change when clicked
		container.add(addBtn);
		
		checkBtn.setBounds(16, 25 + 60 * 1, 80, 40);
		checkBtn.addActionListener(transaction);
		checkBtn.setIcon(new ImageIcon("src/images/ButtonTex/buttonTex.png")); 	//Changes the background image
		checkBtn.setVerticalTextPosition(JButton.CENTER); 						// Sets the text to the middle
	    checkBtn.setHorizontalTextPosition(JButton.CENTER); 						//to avoid it bumping the image around
	    checkBtn.setBackground(Color.BLACK); 			//Sets the background to black
	    checkBtn.setBorder(null); 					//Removes the border around the button
	    checkBtn.setForeground(Color.WHITE); 			//Sets the font color to white
	    checkBtn.setContentAreaFilled(false); 		//Does not allow the background to change when clicked
		container.add(checkBtn);

		clearBtn.setBounds(16, 25 + 60 * 2, 80, 40);
		clearBtn.addActionListener(transaction);
		clearBtn.setIcon(new ImageIcon("src/images/ButtonTex/buttonTex.png")); 	//Changes the background image
	    clearBtn.setVerticalTextPosition(JButton.CENTER); 						// Sets the text to the middle
	    clearBtn.setHorizontalTextPosition(JButton.CENTER); 					//to avoid it bumping the image around
	    clearBtn.setBackground(Color.BLACK); 		//Sets the background to black
	    clearBtn.setBorder(null); 					//Removes the border around the button
	    clearBtn.setForeground(Color.WHITE); 		//Sets the font color to white
	    clearBtn.setContentAreaFilled(false); 		//Does not allow the background to change when clicked
		container.add(clearBtn);

		action.setBounds(110, 235, 270, 20);
		action.setText("Please input the product number and amount.");
		action.setForeground(Color.WHITE);
		container.add(action);

		input.setBounds(110, 25, 200, 40);
		input.setText("");
		input.setBackground(Color.BLACK);
		input.setForeground(Color.WHITE);
		input.setBorder(BorderFactory.createLineBorder(Color.green));
		container.add(input);
		
		inputNo.setBounds(330, 25, 50, 40);
		inputNo.setText("");
		inputNo.setBackground(Color.BLACK);
		inputNo.setForeground(Color.WHITE);
		inputNo.setBorder(BorderFactory.createLineBorder(Color.green));
		container.add(inputNo);

		scrollPane.setBounds(110, 75, 270, 160);
		output.setText("");
		output.setFont(f);
		output.setEditable(false);
		scrollPane.setBorder(null);
		output.setBackground(Color.BLACK);
		output.setForeground(Color.WHITE);
		output.setBorder(BorderFactory.createLineBorder(Color.green));
		container.add(scrollPane);
		scrollPane.getViewport().add(output);

		picture.setBounds(16, 25 + 60 * 3, 80, 80);
		picture.setDefLoc(new Point(16, 25+60*3));
		container.add(picture);
		picture.clear();

		rootWindow.setVisible(true);
		rootWindow.addKeyListener(this);
		input.addKeyListener(this);
		rootWindow.requestFocus();
	}

	class Transaction implements ActionListener {
		public void actionPerformed(ActionEvent ae) {
			if (stock == null) {
				action.setText("No connection");
				return;
			}
			String btnPressed = ae.getActionCommand();
			String inputText = input.getText().trim();
			String inputAm = inputNo.getText().trim();

			try {
				if (btnPressed.equalsIgnoreCase("add")) {
					if (stock.exists(inputText)) {
						if(inputAm.equalsIgnoreCase("")){
							action.setText("Please insert an amount.");
						}else{
						Product product = stock.getDetails(inputText);
							stock.addStock(inputText, Integer.valueOf(inputAm));
							Product pr = stock.getDetails(inputText);
							Date d = new Date(System.currentTimeMillis()); 
							Time t = new Time(System.currentTimeMillis());							
							picture.set(stock.getImage(inputText));
							if(Integer.valueOf(inputAm) > 1){
							output.append(inputAm
									+ " "
									+ pr.getDescription() 	
	            		  			+ "s added."
	            		  			+ "["
	            		  			+ d.toString()
	            		  			+ "||"
	            		  			+ t.toString()
	            		  			+ "]"
	            		  			+ "\n");
							action.setText(inputAm
									+ " "
									+ pr.getDescription() 	
	            		  			+ "s added - "
            		  				+ pr.getQuantity() 	
            		  				+ " now in stock.");
							}else{
								output.append(inputAm
										+ " "
										+ pr.getDescription() 	
		            		  			+ " added."
		            		  			+ "["
		            		  			+ d.toString()
		            		  			+ "||"
		            		  			+ t.toString()
		            		  			+ "]"
		            		  			+ "\n");
								action.setText(inputAm
										+ " "
										+ pr.getDescription() 	
		            		  			+ " added - "
	            		  				+ pr.getQuantity() 	
	            		  				+ " now in stock.");
								
							}
							//Log saving not working.
							//Kept for future development.
							/*try{
								String outputToFile = "";
								String toBeAdded =inputAm
										+ " "
										+ pr.getDescription() 	
		            		  			+ " added."
		            		  			+ "["
		            		  			+ d.toString()
		            		  			+ "||"
		            		  			+ t.toString()
		            		  			+ "]"
		            		  			+ "\n";
								File file = new File("BackdoorLog.txt");
								FileReader fileR = new FileReader(file);
								
								BufferedReader br = new BufferedReader(fileR);
							    
							        String line = br.readLine();
							        if(line == null){
							        	System.err.println("line is null");
							        	//fileW.write(toBeAdded);
							        }
							        while (line != null) {
							        	if(!line.equalsIgnoreCase("null")){
							        	System.err.println("line is not null");
							            line = br.readLine();
							            System.err.println(line);
							            outputToFile+=line;}
							        }
							    
							        br.close();
							        
							        outputToFile += toBeAdded;
									FileWriter fileW = new FileWriter(file);
									fileW.append(outputToFile);									
									fileW.flush();
									fileW.close();
									System.err.println("Log written.");
								} catch (IOException e) {
									System.err.println("Log not written.");
									e.printStackTrace();
								}*/
							}
						}
					} else {
						action.setText("Unknown product number " + inputText);
					}
				
				
				if ( btnPressed.equalsIgnoreCase( "check" ) )
		        {
		          String pn  = input.getText().trim();
		          int    amount  = 1;
		  
		          if ( stock.exists( pn ) )
		          {
		            Product pr = stock.getDetails(pn);
		            if ( pr.getQuantity() >= amount )
		            {
		              action.setText(pr.getDescription()
		            		  			+ " - "
	            		  				+ pr.getQuantity()
	            		  				+ " in stock.");
		              product = pr;
		              product.setQuantity( amount );
		              picture.set(stock.getImage(inputText));
		            } else {
		              action.setText(
		                pr.getDescription() +" not in stock"
		              );
		            }
		          } else {
		            action.setText(
		              "Unknown product number " + pn
		            );
		          }
		        }

				if (btnPressed.equalsIgnoreCase("clear")) {
					action.setText("Please input the product number and amount.");
					input.setText("");
					inputNo.setText("");
					picture.clear();
				}

				//input.requestFocus();
			} catch (StockException e) {
				output.append("Error:" + "\n" + e.getMessage() + "\n");
			}
		}

	}

	@Override
	public void keyPressed(KeyEvent arg0) {
		// TODO Auto-generated method stub
		switch(arg0.getKeyCode()){
		case KeyEvent.VK_ESCAPE:
			System.exit(0);
			break;
		}
		
	}

	@Override
	public void keyReleased(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void keyTyped(KeyEvent arg0) {
		// TODO Auto-generated method stub
		
	}
}
